package com.wt.chat.controller;

import com.wt.chat.cache.RedisCache;
import com.wt.chat.response.ResponseResult;
import com.wt.chat.service.LoginService;
import com.wt.chat.utils.CookieUtils;
import com.wt.chat.utils.Keys;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @description
 * @author: wangtao
 * @date:14:59 2019/11/8
 * @email:taow02@jumei.com
 */
@RestController
@RequestMapping("/login")
public class LoginController {

    @Autowired
    private LoginService loginService;

    @Autowired
    private RedisCache redisCache;

    @RequestMapping("/callback")
    public void doLogin(HttpServletRequest request, HttpServletResponse response) throws IOException {
    	// 获取token参数
		String token = request.getParameter("token");
		Integer uid = redisCache.get(token, Integer.class);
		redisCache.set(token, 1, 24 * 60 * 60);
        CookieUtils.addCookie(response, Keys.LOGIN_COOKIE_KEY, token, -1);
        response.sendRedirect("/index.html");
    }

    /**
     * 获取随机数，5位
     */
    @RequestMapping("/generateNonceStr")
    public ResponseResult getNonceStr() {
        String nonceStr = loginService.generateNonceStr();
        return new ResponseResult().code(StringUtils.isEmpty(nonceStr) ? 1 : 0).body(nonceStr);
    }

}
